package com.ruiysoft.crm.controller;

import cn.taroco.common.utils.Query;
import cn.taroco.common.vo.UserVO;
import cn.taroco.common.web.Response;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ruiysoft.crm.model.dto.BizBookingClientDTO;
import com.ruiysoft.crm.model.entity.BizBookingClient;
import com.ruiysoft.crm.model.entity.SysUser;
import com.ruiysoft.crm.model.vo.BizBookingButton;
import com.ruiysoft.crm.service.BizBookingClientService;
import com.ruiysoft.crm.service.BizClientService;
import com.ruiysoft.crm.service.BizSpecificationService;
import com.ruiysoft.crm.service.SysUserService;
import io.swagger.annotations.Api;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author fanyl
 */
@Api(tags = "预约客户")
@RestController
    @RequestMapping("/booking")
public class BizBookingClientController {

    private final SysUserService sysUserService;
    private final BizSpecificationService bizSpecificationService;

    private final BizBookingClientService bizBookingClientService;

    public BizBookingClientController(BizBookingClientService bizBookingClientService, BizSpecificationService bizSpecificationService, SysUserService sysUserService, BizClientService bizClientService) {
        this.bizBookingClientService = bizBookingClientService;
        this.bizSpecificationService = bizSpecificationService;
        this.sysUserService = sysUserService;
    }

    /**
     * 通过ID查询信息
     *
     * @param id ID
     * @return
     */
    @GetMapping("/get/{id}")
    public BizBookingClient get(@PathVariable Integer id) {
        BizBookingClient bizBookingClient = bizBookingClientService.getById(id);
        if (!ObjectUtils.isEmpty(bizBookingClient)) {
            Map<String, Object> sysDict = bizSpecificationService.getSysDictByValue(bizBookingClient.getFollowStatus(), "booking");
            if (!CollectionUtils.isEmpty(sysDict)) {
                bizBookingClient.setBookingStatus((String) sysDict.get("label"));
            }
        }
        return bizBookingClient;
    }

    /**
     * 分页查询
     *
     * @param params 分页对象
     * @return 分页对象
     */
    @GetMapping("/list/page")
    public IPage dictPage(@RequestParam Map<String, Object> params, UserVO userVO) {
        if(userVO==null){
            userVO=new UserVO();
            userVO.setUsername("hanl");
        }
        String userName = userVO.getUsername();
        SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getUsername, userName));
        params.put("booking.user_id", "'"+sysUser.getUserId()+"'");

       // IPage page = bizBookingClientService.page(new Query<>(params), new QueryWrapper<>());

        IPage page=bizBookingClientService.queryBookingInfo(new Query<>(params),params);
        if (!CollectionUtils.isEmpty(page.getRecords())) {
            List<BizBookingClientDTO> bizBookingClients = page.getRecords();
            bizBookingClients.forEach(bizBookingClient -> {
                Map<String, Object> sysDict = bizSpecificationService.getSysDictByValue(bizBookingClient.getFollowStatus(), "booking");
                if (!CollectionUtils.isEmpty(sysDict)) {
                    bizBookingClient.setBookingStatus((String) sysDict.get("label"));
                }
                if (StringUtils.hasText(bizBookingClient.getIdNo())) {
                    bizBookingClient.setIdNo(bizBookingClient.getIdNo().replaceAll("(\\d{4})\\d{10}(\\w{4})", "$1*****$2"));
                }

                if (StringUtils.hasText(bizBookingClient.getMobilePhone())) {
                    bizBookingClient.setMobilePhone(bizBookingClient.getMobilePhone().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
                }

                if (StringUtils.hasText(bizBookingClient.getStandbyMobile())) {
                    bizBookingClient.setStandbyMobile(bizBookingClient.getStandbyMobile().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
                }
            });
            page.setRecords(bizBookingClients);
        }
        return page;
    }
@GetMapping("/getUnReadList")
    public Response getUnReadList(UserVO userVO){
        return Response.success(bizBookingClientService.getUnReadList(userVO));
    }

    /**
     * 添加
     *
     * @param bizBookingClient
     * @return success、false
     */
    @PostMapping("/insert")
    public Response add(@RequestBody BizBookingClient bizBookingClient) {
        bizBookingClient.setCreateDate(LocalDateTime.now());
        return Response.success(bizBookingClientService.save(bizBookingClient));
    }

    /**
     * 添加
     *
     * @param bizBookingClient
     * @return success、false
     */
    @PostMapping("/insertBookingByClientId")
    public Response addBookingByClientId(@RequestBody BizBookingClient bizBookingClient, UserVO userVO) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime bookingDate = bizBookingClient.getBookingTime();
        return Response.success(bizBookingClientService.addBookingByClientId(bizBookingClient.getClientId(), bookingDate, userVO));
    }

    /**
     * 删除
     *
     * @param id ID
     * @return R
     */
    @DeleteMapping("/delete/{id}")
    public Response delete(@PathVariable Integer id) {
        return Response.success(bizBookingClientService.removeById(id));
    }

    /**
     * 修改
     *
     * @param bizBookingClient
     * @return success/false
     */
    @PutMapping("/update")
    public Response editDict(@RequestBody BizBookingClient bizBookingClient) {
        bizBookingClient.setModificationDate(LocalDateTime.now());
        return Response.success(bizBookingClientService.updateById(bizBookingClient));
    }

    /**
     * 根据主键修改预约读取状态 readStatus 0 未读,1 已读
     *
     * @param id
     * @return success/false
     */
    @PutMapping("/changeStatusById")
    public Response changeStatusById(String id) {
        return Response.success(bizBookingClientService.changeStatusById(id));
    }

    @GetMapping("/getBookingCountByDate")
    public Response getBookingCountByDate(String date,String type,UserVO userVO){
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime date1=LocalDateTime.parse(date,df);
        String userName=userVO!=null ? userVO.getUsername(): "hanl";
        return Response.success(bizBookingClientService.getBookingCountByDate(date1,type,userName));
    }

    @GetMapping("/getBookingCountByUserId")
    public Response getBookingCountByUserId(UserVO userVO){
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime date1=LocalDateTime.now();
        String userName=userVO!=null ? userVO.getUsername(): "hanl";

        List<BizBookingButton> buttons=new ArrayList<>();
        String[] buttonLable={"今天","明天","后天","三天后","四天后","五天后","六天后","七天后"};

        for (int i = 0; i < buttonLable.length; i++) {
            date1= LocalDateTime.now().minusDays(0-i);
            Object ob=bizBookingClientService.getBookingCountByDate(date1,"1",userName);
            BizBookingButton bookingButton=new BizBookingButton();
            bookingButton.setButtonLable(buttonLable[i]);
            bookingButton.setDate(date1.toLocalDate());
            bookingButton.setNumber(ob.toString());
            bookingButton.setSelectType("1");
            buttons.add(bookingButton);
        }

        Object ob=bizBookingClientService.getBookingCountByDate(LocalDateTime.now(),"0",userName);
        BizBookingButton bookingButton=new BizBookingButton();
        bookingButton.setButtonLable("逾期");
        bookingButton.setDate(LocalDateTime.now().toLocalDate());
        bookingButton.setNumber(ob.toString());
        bookingButton.setSelectType("0");
        buttons.add(bookingButton);

        return Response.success(buttons);
    }
}
